﻿#include "productlibrarytableview.h"
#include "readonlydelegate.h"

ProductLibraryTableView::ProductLibraryTableView(QWidget *parent) : MyTableView(parent)
{
    setSortingEnabled(true);
    model = new ProductLibraryStandardItemModel();
    setModel(model);
    setSelectionRow();

    for(int i=0;i<model->columnCount();i++){
        if(i!=11){
            setItemDelegateForColumn(i, new ReadOnlyDelegate);
        }
    }

    connect(this, &QTableView::doubleClicked,
            [=](const QModelIndex index)
    {
        if(index.row() == model->rowCount()-1){
            productPicker.showAndInit();
        }
    });

    connect(&productPicker, &ProductPicker::selectedFinished,
            [=](QList<Product*> products, int defaultCount)
    {
        if(defaultCount < 0)defaultCount=0;
        model->insertProduct(products, defaultCount);
    });

    connect(model, &ProductLibraryStandardItemModel::updateTotalValue,
            [=](int totalCount, double totalMoney)
    {
        emit this->updateTotalValue(totalCount, totalMoney);
    });
}

void ProductLibraryTableView::initHiddenState(){
    initHiddenStateList("productLibrary", model->header.size());
}

void ProductLibraryTableView::setListPushButton(ListPushButton *listPushButton){
    setListPushButtonAndMenuLabel(listPushButton, model->header);
}

void ProductLibraryTableView::setSelectionRow(){
    model->appendRow(*(new QList<QStandardItem*>));
    setSpan(model->rowCount()-1, 0, 1, model->columnCount());
}

void ProductLibraryTableView::clear(){
    model->reset();
    setSelectionRow();

    refreshHiddenState();
}

QList<Product*> ProductLibraryTableView::currentProducts(){
    return model->currentProducts();
}

void ProductLibraryTableView::loadSanbaoProducts(){
    clear();
    DbHelper helper;
    model->insertProduct(helper.getSanbaoProducts(), 0);
}
